import java.io.*;
import java.net.Socket;

public class ServiceThread extends Thread {
    private Socket socket;
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }
    public ServiceThread(Socket socket) {
        super();
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            BufferedWriter wFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D://messagesT.txt",true)));//将内容写入到文件中
            //使用输入输出流进行通信
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String strOut = "";
            String strIn = "";
            while(true){
                strIn = socket.getInetAddress().getHostName()+":"+br.readLine();
                strOut = strIn;
                wFile.write(strIn);
                wFile.newLine();
                wFile.flush();
                //遍历在线的链接请求，发送内容
                for (Socket soc : Service.list) {
                    if(soc != socket){
                        if(strOut.contains("file")){
                            //创建FileInputStream对象实例，将要发送的文件写入到输出流数据缓冲区中
                            File file=new File("E:/dd/a.txt");
                            FileInputStream fis = new FileInputStream(file);
                            OutputStream oo=null;
                            byte[] b=new byte[1024];
                            int len;
                            while((len=fis.read(b))!=-1){
                                oo.write(b, 0, len);
                            }
                            //告知客户端发送的数据完毕。
                            socket.shutdownOutput();
                        }else {
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
                            bw.write(strOut);
                            System.out.println(strOut);
                            bw.newLine();
                            bw.flush();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}